const log = require('../../util/log')
const chromeMng = require('../chromeMng.20180824')
const {
  Network,
  Page,
  DOM,
  Runtime,
  Emulation
} = chromeMng.client;

async function getHtml(obj) {
  if (!obj.url) {
    return new Promise((resolve, reject) => {
      reject('缺少url')
    })
  }
  chromeMng.isLoadEventFired = false
  await Page.navigate({
    url: obj.url
  })
  return step2(obj)
}

async function step2(obj) {
  if (!chromeMng.isLoadEventFired) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        step2(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      })
    })
  }
  var document = await DOM.getDocument();
  return new Promise(resolve => {
    DOM.getOuterHTML({
      nodeId: document.root.nodeId
    }).then(({outerHTML}) => {
      resolve(outerHTML)
    })
  })
}

module.exports = getHtml
